<script setup>
import { message, Modal } from "ant-design-vue";
import { ref, onMounted, reactive, computed, h } from "vue";
import { useStore } from "vuex";
import { deleteServer, getServerList } from "@/api/server";
import ServerEditor from "./editor/ServerEditor.vue";
import { isPagExceeded } from "@/utils/pagination";
import ServerStateEditor from "./editor/ServerStateEditor.vue";
import { getUser } from "@/api/user";
import { DownOutlined } from "@ant-design/icons-vue";
import ServerTitleEditor from "./editor/ServerTitleEditor.vue";

const columns = [
  {
    title: "ID",
    dataIndex: "id",
  },
  {
    title: "服务器名称",
    dataIndex: "name",
  },
  {
    title: "头衔",
    dataIndex: "title",
  },
  {
    title: "所属玩家名",
    dataIndex: "user.playerName",
  },
  {
    title: "服务器IP",
    dataIndex: "serverAddr",
  },
  {
    title: "服务器版本",
    dataIndex: "serverVersion",
  },
  {
    title: "服务器状态",
    dataIndex: "serverState",
    slots: { customRender: "serverState" },
  },
  {
    title: "快捷操作",
    slots: { customRender: "action" },
  },
];

const dataSource = ref([]);
const editor = ref();
const stateEditor = ref();
const titleEditor = ref();

const store = useStore();
const filterParam = reactive({
  state: null,
  username: "",
  email: "",
  serverName: "",
  showAll: false,
  orderBy: false,
});

const loginUser = computed(() => store.state.loginUser);
const fetchServerList = async () => {
  loading.value = true;

  let {
    data: { data: pag },
  } = await getServerList(pagination.current, filterParam);
  if (isPagExceeded(pag)) {
    pagination.current = pag.total;
    fetchServerList();
    return;
  }

  dataSource.value = pag.records;
  pagination.pageSize = pag.size;
  pagination.total = pag.total;
  loading.value = false;
};
const handleDelete = async (id) => {
  let { data } = await deleteServer(id);
  if (data.code != 200) {
    message.error(data.message);
    return;
  }
  message.success(data.message);
  fetchServerList();
};

const loading = ref(true);
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 20,
  showQuickJumper: true,
  showTotal: (total) => `Total ${total} items`,
});
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  fetchServerList();
};
const fetchUser = async (id) => {
  console.log(id);
  let { data } = await getUser(id);
  // console.log(data.data);
  Modal.success({
    title: () => "获取用户成功",
    content: () => h("pre", JSON.stringify(data.data, null, 2)),
  });
};
const showImgUrl = (record) => {
  Modal.info({
    title: () => "图片地址",
    content: () => h("div", {}, [h("p", "展示图: " + record.imgShow), h("p", "大图: " + record.imgFull)]),
  });
};

onMounted(() => {
  fetchServerList();
});
</script>

<template>
  <server-editor ref="editor" @finished="fetchServerList()" />
  <server-state-editor ref="stateEditor" @finished="fetchServerList()" />
  <server-title-editor ref="titleEditor" @finished="fetchServerList()"></server-title-editor>

  <page-header-wrapper>
    <template #pageHeader>
      <a-page-header title="服务器列表" sub-title="我发布的服务器" />
    </template>
    <a-card title="快捷操作">
      <a-alert
        v-if="loginUser.userRole >= 2"
        message="您目前正在使用管理员账号,将展示所有的服务器"
        type="warning"
        closable
      />
      <br />
      <a-space>
        <a-button @click="editor.init()">添加服务器</a-button>
        <span>状态: </span>
        <a-select ref="select" v-model:value="filterParam.state" style="width: 120px">
          <a-select-option :value="null">全部</a-select-option>
          <a-select-option value="1">等待审核</a-select-option>
          <a-select-option value="2">已通过</a-select-option>
          <a-select-option value="3">已拒绝</a-select-option>
        </a-select>
        <span>服务器名: </span>
        <a-input v-model:value="filterParam.serverName" />
        <span>用户名: </span>
        <a-input v-model:value="filterParam.username" />
        <span>邮箱: </span>
        <a-input v-model:value="filterParam.email" />
        <span>倒序: </span>
        <a-switch v-model:checked="filterParam.orderBy" @change="fetchServerList()" />
        <a-button type="primary" @click="fetchServerList()">查询</a-button>
      </a-space>
    </a-card>
    <a-card title="服务器列表" style="margin-top: 16px">
      <a-table
        rowKey="id"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #action="{ record }">
          <a-space>
            <template v-if="!filterParam.showAll">
              <a-button @click="editor.init(record.id)" type="primary">编辑</a-button>
              <a-popconfirm title="请确认是否删除" ok-text="Yes" cancel-text="No" @confirm="handleDelete(record.id)">
                <a-button danger>删除</a-button>
              </a-popconfirm>
            </template>
            <a-button @click="showImgUrl(record)" type="primary">获取图片地址</a-button>

            <a-dropdown v-if="loginUser.userRole >= 2">
              <a class="ant-dropdown-link" @click.prevent>
                管理员操作
                <DownOutlined />
              </a>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="stateEditor.init(record.id)" key="0"> 修改状态 </a-menu-item>
                  <a-menu-item @click="titleEditor.init(record.id)" key="1"> 修改头衔 </a-menu-item>
                  <a-menu-item @click="fetchUser(record.userId)" key="2"> 获取所属用户 </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </template>
        <template #serverState="{ record }">
          <a-tag color="orange" v-if="record.serverState == 1">等待审核</a-tag>
          <a-tag color="green" v-else-if="record.serverState == 2">已通过</a-tag>
          <a-tag color="red" v-else-if="record.serverState == 3">已拒绝</a-tag>
        </template>
      </a-table>
    </a-card>
  </page-header-wrapper>
</template>
